package com.cloudfast.email.impl;

import com.cloudfast.common.date.DateUtils;
import com.cloudfast.config.EmailDataSource;
import com.cloudfast.email.JEmailSender;
import com.cloudfast.email.text.EmailMessage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JEmailDataSourceSenderImpl implements JEmailSender {
    private EmailDataSource dataSource;

    private String username;

    private static final Logger logger = LoggerFactory.getLogger(Logger.class);

    public JEmailDataSourceSenderImpl(EmailDataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public boolean sendTextMail(EmailMessage emailMessage) {
        try {
            JavaMailSender javaMailSender = initSender();
            // 创建邮件内容
            SimpleMailMessage message = new SimpleMailMessage();
            // 这里指的是发送者的账号
            message.setFrom(username);
            message.setTo(emailMessage.getRevUser().split(","));
            if (StringUtils.isNotEmpty(emailMessage.getCcUser())) {
                message.setCc(emailMessage.getCcUser().split(","));
            }
            if (StringUtils.isNotEmpty(emailMessage.getTitle())) {
                message.setSubject(emailMessage.getTitle());
            }
            if (StringUtils.isNotEmpty(emailMessage.getContent())) {
                message.setText(emailMessage.getContent());
            }
            // 发送邮件
            javaMailSender.send(message);
            return true;
        } catch (Exception e) {

        }
        return false;
    }

    @Override
    public boolean sendHtmlMail(EmailMessage emailMessage) {
        try {
            JavaMailSender javaMailSender = initSender();
            MimeMessage message = javaMailSender.createMimeMessage();
            // 创建邮件内容 true 表示创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(username);
            helper.setSubject(emailMessage.getTitle());
            if (StringUtils.isNotEmpty(emailMessage.getCcUser())) {
                helper.setCc(emailMessage.getCcUser().split(","));
            }
            if (StringUtils.isNotEmpty(emailMessage.getTitle())) {
                helper.setSubject(emailMessage.getTitle());
            }
            if (StringUtils.isNotEmpty(emailMessage.getContent())) {
                helper.setText(emailMessage.getContent(), true);
            }
            // 发送邮件
            javaMailSender.send(message);

        } catch (Exception e) {

        }

        return false;
    }

    private JavaMailSender initSender() throws Exception {
        JavaMailSenderImpl jEmailSender = new JavaMailSenderImpl();
        List<Map<String, Object>> tableExsit = queryList("SHOW TABLES LIKE 'sys_email_conf'", null);
        if (tableExsit != null && tableExsit.size() > 0) {
            List<Map<String, Object>> list = queryList("select * from sys_email_conf order by id desc", null);
            if (list != null && list.size() > 0) {
                Map<String, Object> map = list.get(0);
                jEmailSender.setHost(map.get("host") + "");
                jEmailSender.setPassword(map.get("password") + "");
                jEmailSender.setUsername(map.get("username") + "");
                jEmailSender.setPort(Integer.parseInt(map.get("port") + ""));
                username = map.get("username").toString();
            }else{
                logger.error("sys_email_conf 配置错误;请确认host,port,username,password 字段是否不为空!");
            }
        } else {
            logger.error(" datasource 模式: 创建sys_email_conf 字段 id: int,username:varchar,password:varchar,port:int,host: varchar");
        }

        return jEmailSender;
    }


    /**
     * 查询列表
     *
     * @param sql
     * @param params
     * @return
     * @throws Exception
     */
    private List<Map<String, Object>> queryList(String sql, Map<String, Object> params) throws Exception {
        List<Map<String, Object>> list = null;

        try (Connection con = dataSource.getConnection();
             PreparedStatement pst = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
                     ResultSet.CONCUR_UPDATABLE);) {
            setParams(pst, params);
            try (ResultSet rs = pst.executeQuery()) {
                ResultSetMetaData md = rs.getMetaData();
                // 返回此 ResultSet 对象中的列数
                int columnCount = md.getColumnCount();
                if (rs.next()) {
                    rs.beforeFirst();
                    list = new ArrayList<>();
                    while (rs.next()) {
                        Map<String, Object> rowData = new HashMap<>(columnCount);
                        if (columnCount == 1) {
                            if (rs.getObject(1) == null) {
                                list = null;
                            } else {
                                rowData.put(md.getColumnName(1), rs.getObject(1));
                                if (list != null) {
                                    list.add(rowData);
                                }
                            }
                        } else {
                            for (int i = 1; i <= columnCount; i++) {
                                if (rs.getObject(i) != null) {
                                    rowData.put(md.getColumnName(i), rs.getObject(i));
                                    if (rs.getObject(i).getClass().getTypeName().equals("java.time.LocalDateTime")) {
                                        String columnValaue = rs.getObject(i).toString().replace("T", " ");
                                        if (columnValaue.length() < 19) {
                                            columnValaue = columnValaue + ":00";
                                        }
                                        columnValaue = DateUtils.dateToString(
                                                DateUtils.stringToDate(columnValaue, DateUtils.DATETIMEFORMAT),
                                                DateUtils.DATETIMEFORMAT);
                                        rowData.put(md.getColumnName(i), columnValaue);
                                    }

                                } else {
                                    rowData.put(md.getColumnName(i), "");
                                }
                            }
                            if (list != null) {
                                list.add(rowData);
                            }
                        }
                    }
                }
                rs.close();

            }

        }
        return list;
    }

    /**
     * 设置参数
     *
     * @param pst
     * @param params
     */
    private void setParams(PreparedStatement pst, Map<String, Object> params) {
        if (params != null) {
            int i = 1;
            try {
                for (String key : params.keySet()) {
                    if (params.get(key) instanceof java.lang.Integer) {
                        pst.setInt(i, Integer.parseInt(params.get(key).toString()));
                    } else if (params.get(key) instanceof java.lang.Long) {
                        pst.setInt(i, Integer.parseInt(params.get(key).toString()));
                    } else if (params.get(key) instanceof java.lang.Double) {
                        pst.setDouble(i, Double.parseDouble(params.get(key).toString()));
                    } else if (params.get(key) instanceof java.util.Date) {
                        pst.setString(i, params.get(key).toString());
                    } else {
                        pst.setString(i, params.get(key).toString());
                    }
                    i++;
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
    }
}
